package com.example.healthcode2;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.KeyEvent;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.healthcode2.Fragment.oneFragment;
import com.example.healthcode2.Fragment.threeFragment;
import com.example.healthcode2.Fragment.twoFragment;
import com.example.healthcode2.Other.ActivityCollector;
import com.example.healthcode2.Other.GpsService;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
//主页面Activity
public class MainActivity extends AppCompatActivity implements threeFragment.ExitOutListener,oneFragment.IntoListener{

    private ViewPager mViewPager;
    private RadioGroup mTabRadioGroup;//导航栏
    private TextView textView_title;

    private List<Fragment> mFragments;
    private FragmentPagerAdapter mAdapter;
    private String[] title={"健康码","疫情信息","我的"};
    private String name;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActivityCollector.addActivity(this);
        if (getSupportActionBar() != null){
            getSupportActionBar().hide();
        }
        Intent intent=getIntent();
        name= (String) intent.getSerializableExtra("name");//获取参数
        initView();//初始化
        startGpsService();//开始定位服务
    }



    private void initView() {
        // find view
        mViewPager = findViewById(R.id.fragment_vp);
        mTabRadioGroup = findViewById(R.id.tabs_rg);
        textView_title=findViewById(R.id.text_title);
        // init fragment
        mFragments = new ArrayList<>(3);
        mFragments.add(new oneFragment());
        mFragments.add(new twoFragment());
        mFragments.add(new threeFragment());

        // init view pager
        mAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), mFragments);
        mViewPager.setAdapter(mAdapter);
        // register listener
        mViewPager.addOnPageChangeListener(mPageChangeListener);
        mTabRadioGroup.setOnCheckedChangeListener(mOnCheckedChangeListener);
    }


    //打开定位服务
    private void startGpsService() {
        requestPowerlocation();
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (!isGpsAble(lm)) {
            Toast.makeText(MainActivity.this, "请打开GPS~", Toast.LENGTH_SHORT).show();
            openGPS2();
        }
        Intent it = new Intent(this, GpsService.class);
        it.putExtra("name",name);
        startService(it);
    }

    private boolean isGpsAble(LocationManager lm) {
        return lm.isProviderEnabled(LocationManager.GPS_PROVIDER) ? true : false;
    }

    //打开设置页面让用户自己设置
    private void openGPS2() {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivityForResult(intent,0);
    }

    public void requestPowerlocation() {
//判断是否已经赋予权限
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            //如果应用之前请求过此权限但用户拒绝了请求，此方法将返回 true。
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {//这里可以写个对话框之类的项向用户解释为什么要申请权限，并在对话框的确认键后续再次申请权限.它在用户选择"不再询问"的情况下返回false
            } else {
                //申请权限，字符串数组内是一个或多个要申请的权限，1是申请权限结果的返回参数，在onRequestPermissionsResult可以得知申请结果
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION,}, 1);
            }
        }
    }
    //写入文件
    public  void writefile(String filename,String text) throws IOException {
        System.out.println("filename:"+filename+" text:"+text);
        OutputStream out=openFileOutput(filename, Context.MODE_PRIVATE);//覆盖
        byte[] bytes = text.getBytes();
        out.write(bytes, 0, bytes.length);
        out.close();
    }

    //返回name给oneFragment
    @Override
    public String Getnameforone(){
        return name;
    }
    //回调接口 执行退出账号 threeFragment
    @Override
    public void deleteUser() throws IOException {
        writefile("name.txt","");
        writefile("password.txt","");
        Intent it = new Intent(this, GpsService.class);
        stopService(it);//结束服务
        finish();//结束Activity

    }
//回调接口 返回name给threeFragment
    @Override
    public String Getnameforthree() {
        return name;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mViewPager.removeOnPageChangeListener(mPageChangeListener);
        ActivityCollector.removeActivity(this);
    }
//ViewPager监听
    private ViewPager.OnPageChangeListener mPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            RadioButton radioButton = (RadioButton) mTabRadioGroup.getChildAt(position);//获取该页面对应的radioButton
            radioButton.setChecked(true);//选中radioButton
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };
//RadioGroup监听
    private RadioGroup.OnCheckedChangeListener mOnCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            for (int i = 0; i < group.getChildCount(); i++) {//遍历radioButton
                if (group.getChildAt(i).getId() == checkedId) {//获取选中的radioButton
                    mViewPager.setCurrentItem(i);//设置对应的viewpage页面
                    textView_title.setText(title[i]);//设置对应的标题
                    return;
                }
            }
        }
    };



    private class MyFragmentPagerAdapter extends FragmentPagerAdapter {

        private List<Fragment> mList;

        public MyFragmentPagerAdapter(FragmentManager fm, List<Fragment> list) {
            super(fm);
            this.mList = list;
        }

        @Override
        public Fragment getItem(int position) {
            return this.mList == null ? null : this.mList.get(position);
        }

        @Override
        public int getCount() {
            return this.mList == null ? 0 : this.mList.size();
        }
    }



    private static boolean isExit = false;//判断返回键是否按下标记
    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //实现按两下返回键退出
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isExit) {
                isExit = true;
                Toast.makeText(getApplicationContext(), "再按一次退出程序",
                        Toast.LENGTH_SHORT).show();
                // 利用handler延迟发送更改状态信息
                mHandler.sendEmptyMessageDelayed(0, 2000);
            } else {
                finish();
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);}
}
